﻿using System;
using System.Collections.Generic;
using System.Text;
using eslib.DataRetrievalLib.Matchers;

namespace eslib.nnp5.AT
{
    /// <summary>
    /// AT指令系统抽象基类
    /// </summary>
    public abstract class ATCommandSystemBase
    {
        ATMatcher matcher = new ATMatcher();
        ATParamSplitor splitor = new ATParamSplitor();

        /// <summary>
        /// 
        /// </summary>
        public ATCommandSystemBase()
        {
            matcher.matchEvent += Matcher_matchEvent;
        }


        /// <summary>
        /// 输入流
        /// </summary>
        /// <param name="b"></param>
        public void inStream(byte b)
        {
            matcher.inStream(b);
        }

        /// <summary>
        /// 输入流
        /// </summary>
        /// <param name="buf"></param>
        public void inStream(byte[] buf)
        {
            matcher.inStream(buf);
        }


        /// <summary>
        /// AT匹配事件
        /// </summary>
        /// <param name="buf"></param>
        private void Matcher_matchEvent(byte[] buf)
        {
            try
            {
                string at = Encoding.ASCII.GetString(buf);

                ATResult res = splitor.Split(at);
                ATHandler(res);
            }
            catch (ATException ate)
            {
                ATErrorEvent?.Invoke(ate.Message);
            }
        }


        /// <summary>
        /// AT处理方法
        /// </summary>
        /// <param name="result"></param>
        public abstract void ATHandler(ATResult result);

        /// <summary>
        /// AT异常时引发
        /// </summary>
        public event ATErrorEventDelegate ATErrorEvent;
    }

    public delegate void ATErrorEventDelegate(string msg);
}
